//
//  LoginViewController.m
//  SAP
//
//  Created by 中矿科技有限公司 on 17/9/12.
//  Copyright © 2017年 中矿科技有限公司. All rights reserved.
//

#import "LoginViewController.h"
#import "PassWordTool.h"

@interface LoginViewController ()

@end

NSString * const KEY_USERNAME_PASSWORD = @"com.company.app.usernamepassword";
NSString * const KEY_USERNAME = @"com.company.app.username";
NSString * const KEY_PASSWORD = @"com.company.app.password";

@implementation LoginViewController
{
    AFHTTPData *_http;
    MBProgressHUD *_waitHud;
}

#pragma mark - LifeCycle

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.passwordField.secureTextEntry =YES;
    BOOL shouldAutoLogin = YES;
    
    [self.accountField setText:[PassWordTool readPassWord:KEY_USERNAME]];
    [self.passwordField setText:[PassWordTool readPassWord:KEY_PASSWORD]];
    _http =[[AFHTTPData alloc]init];
    
    if ( [UserManager sharedInstance].lastConnectionStatus == ZYDConnectionStatusMannualLogout || [UserManager sharedInstance].lastConnectionStatus == ZYDConnectionStatusForceLogout) {
        /// 被踢或者登出后，不要自动登录
        shouldAutoLogin = NO;
    }
    if (shouldAutoLogin && self.accountField.text.length > 0 && self.passwordField.text.length > 0 ) {
        [self onClickedLoginBtn:nil];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - UITableViewDelegate

#pragma mark - Public

#pragma mark - Private
- (IBAction)onClickedLoginBtn:(UIButton *)sender {
    [self.view endEditing:YES];
    [PassWordTool savePassWord:self.accountField.text keyStr:KEY_USERNAME];
    [PassWordTool savePassWord:self.passwordField.text keyStr:KEY_PASSWORD];

    _waitHud=[[MBProgressHUD alloc] initWithView:self.view];//加载
    [self.view addSubview:_waitHud];
    [_waitHud showAnimated:YES];
    _waitHud.label.text =nil;
    [_waitHud showAnimated:YES];
    
    NSMutableDictionary *batchDict =[[NSMutableDictionary alloc]init];
    [batchDict setObject:@"" forKey:@"detailContent"];
    [batchDict setObject:self.accountField.text forKey:@"usernameOrEmailAddress"];
    [batchDict setObject:self.passwordField.text forKey:@"password"];

    [_http postDataWithUrl:SAPLoginKUrl httpBobyData:batchDict onSuccess:^(NSData *data) {
        
        [_waitHud showAnimated:NO];
        [_waitHud hideAnimated:NO afterDelay:2.0f];
        
        NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if ([dict[@"success"] integerValue] ==1) {
            [_waitHud showAnimated:NO];
            [_waitHud hideAnimated:YES];
            [UserManager sharedInstance].token = [@"Bearer " stringByAppendingString: dict[@"result"]];
            [self prepareUserProfile];
            [[AppDelegate sharedAppDelegate] enterMainUI];
        }else{
            _waitHud.label.text =dict[@"error"][@"message"];
            [_waitHud showAnimated:NO];
            [_waitHud hideAnimated:NO afterDelay:2.0f];
        }
    } onFailure:^(NSError *error) {
        _waitHud.label.text =@"网络异常,请重试";
        [_waitHud showAnimated:NO];
        [_waitHud hideAnimated:NO afterDelay:2.0f];
    }];
    
}

-(void)prepareUserProfile{
    [_http postTokenDataWithUrl:SAPUserProfileKUrl httpBobyData:nil onSuccess:^(NSData *data) {
        NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if ([dict[@"success"] integerValue] ==1) {
            [[UserManager sharedInstance] login:dict[@"result"]];
        }

    } onFailure:^(NSError *error) {
        
    }];
}


#pragma mark - Getter

#pragma mark - Setter

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
